<template>
  <div>
    <textarea
      id="copy"
      style="position: absolute; left: -999999px; top: -999999px"
    ></textarea>
    <div class="fileUpload">
      <div class="uploadItme">
        <el-upload
          v-loading="loading"
          :element-loading-text="loadingtext"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.8)"
          class="upload-demo"
          accept=".zip,.gz"
          drag
          action=""
          :show-file-list="false"
          :http-request="httpRequest"
        >
          <div>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">拖拽或 <em>点击上传</em></div>
          </div>
          <template #tip>
            <div class="el-upload__tip">只能上传.zip/.gz的文件</div>
          </template>
        </el-upload>
      </div>
      <div class="parserFile">
        <div class="title">文件解析进度</div>
        <el-progress
          type="dashboard"
          :percentage="percentageMD5"
          :color="colors"
        />
      </div>
      <div class="uploadFile">
        <div class="title">文件上传进度</div>
        <el-progress
          type="dashboard"
          :percentage="percentageUpload"
          :color="colors"
        />
      </div>
    </div>
    <div class="list">
      <div v-for="(item, index) in list" :key="index">
        <el-row :gutter="20">
          <el-col :span="6">永久不限速地址</el-col>
          <el-col :span="6"> {{ item.name }}</el-col>
          <el-col :span="6"
            ><el-button @click="copyItme(item.id)">复制</el-button></el-col
          >
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>
import { fileChunks, fileValidationMD5 } from "@/utils/fileUtils.js";
import {
  fileCheck,
  fileUpload,
  fileUploadMerge,
  downLoadPathStr,
} from "@/api/article.js";
import { toRefs, reactive } from "vue";
import { ElMessage } from "element-plus";
export default {
  name: "fileUpload",
  setup() {
    const data = reactive({
      percentageMD5: 0,
      percentageUpload: 0,
      fileMD5: "", //文件的唯一标识
      colors: [
        { color: "#f56c6c", percentage: 30 },
        { color: "#e6a23c", percentage: 65 },
        { color: "#5cb87a", percentage: 100 },
      ],
      list: [],
      loadingtext: "上传中-请稍后",
      loading: false,
    });
    function copyItme(item) {
      var text = "";
      text = downLoadPathStr(item);
      var input = document.getElementById("copy");
      console.log(item);
      input.value = text;
      input.select();
      document.execCommand("copy"); // 执行浏览器复制命令
      ElMessage.success("复制成功");
    }
    function getnum(num) {
      return Math.round(num * 100) / 100;
    }
    async function httpRequest(params) {
      /**
       * file,fileName,countChunk,flieChunks
       */
      const { flieChunks, countChunk, fileName } = fileChunks(params.file, 50);
      data.loading = true;
      const fileMD5 = await fileValidationMD5(flieChunks, (progress) => {
        data.percentageMD5 = Math.ceil(progress * 100);
      });
      data.percentageMD5 = 100;
      data.fileMD5 = fileMD5;
      var fileCheckRes = await fileCheck({
        fileMD5: fileMD5,
        countChunk: countChunk,
        fileName: fileName,
      });
      if (fileCheckRes.code == 200 || fileCheckRes.code == 201) {
        var uploadList = flieChunks;
        // 201可以进行断点续传
        if (fileCheckRes.code == 201) {
          let { hasFileList } = fileCheckRes.data;
          if (hasFileList.length >= 2) {
            hasFileList = hasFileList.slice(0, hasFileList.length - 1);
            uploadList = uploadList.filter(
              (item) =>
                !hasFileList.some(
                  (temporaryFile) => item.index == temporaryFile
                )
            );
          }
        }
        var start = getnum(Number(1 - uploadList.length / countChunk)) * 100;
        data.percentageUpload = start;
        for (let i = 0; i < uploadList.length; i++) {
          let percentageUploadUp = data.percentageUpload;
          const element = uploadList[i];
          var form = new FormData();
          form.append("fileMD5", fileMD5);
          form.append("file", element.fileChunk);
          form.append("index", element.index);
          try {
            await fileUpload(form, (progress) => {
              data.percentageUpload = getnum(
                percentageUploadUp + parseInt(progress) / countChunk
              );
            });
            data.percentageUpload = getnum(
              Number((i + 1) / uploadList.length) * 100 + start
            );
            percentageUploadUp = data.percentageUpload;
          } catch (error) {
            console.log(error);
            break;
          }
        }
        data.percentageUpload = 100;
        let fileUploadMergeRes = await fileUploadMerge({
          fileMD5: fileMD5,
          countChunk: countChunk,
          fileName: fileName,
        });
        if (fileUploadMergeRes.code == 200) {
          ElMessage({
            message: "上传成功！",
            type: "success",
          });
          data.list.push({
            id: fileUploadMergeRes.data,
            name: fileName,
          });
        } else if (fileUploadMergeRes.code == 201) {
          ElMessage({
            message: fileUploadMergeRes.msg,
            type: "warning",
          });
        }
        data.loading = false;
      } else if (fileCheckRes.code == 203) {
        //文件之前存在直接拷贝路径即可
        data.percentageUpload = 100;
        data.list.push({
          id: fileCheckRes.data,
          name: fileName,
        });
        data.loading = false;
      }
      setTimeout(() => {
        data.percentageMD5 = 0;
        data.percentageUpload = 0;
      }, 1000);
    }
    return { ...toRefs(data), httpRequest, copyItme };
  },
};
</script>
<style lang="scss">
.el-row {
  margin-top: 20px;
}
</style>
<style lang="scss" scoped>
.fileUpload {
  overflow: hidden;
  .uploadItme,
  .parserFile,
  .uploadFile {
    float: left;
  }
  .parserFile,
  .uploadFile {
    margin-left: 50px;
    .title {
      padding: 25px 0;
      text-align: center;
    }
  }
}
</style>
